const setCookie = (c_name, value, expiredays, domain) => {
  let exdate = new Date()
  exdate.setDate(exdate.getDate() + expiredays)
  document.cookie = c_name + '=' + encodeURI(escape(value)) + ((expiredays == null) ?
    '' :
    ';expires=' + exdate.toGMTString()) + ((domain == null) ?
    '' :
    ';domain=' + domain) + '; path=/'
}
const getCookie = (c_name, pure) => {
  if(document.cookie.length > 0) {
    let c_start = document.cookie.indexOf(c_name + '=')
    if(c_start != -1) {
      c_start = c_start + c_name.length + 1
      let c_end = document.cookie.indexOf(';', c_start)
      if(c_end == -1)
        c_end = document.cookie.length
      if(pure) {
        return unescape(decodeURI(document.cookie.substring(c_start, c_end)))
      }
      return JSON.parse(unescape(decodeURI(document.cookie.substring(c_start, c_end))))
    }
  }
  return ''
}

function pwdReg(str) {
  var reg = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,32}$/;
  return reg.test(str);
}

function emailReg(str) {
  var reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
  return reg.test(str);
}

function mobileReg(str) {
  var reg = new RegExp('^1(3|4|5|7|8)[0-9]{9}$');
  return reg.test(str);
}
String.prototype.format = function() {
  var a = arguments;
  return this.replace(/{(\d+)}/g, function(m, i) {
    return a[i]
  })
};
String.prototype.padLeft = function(padchar, num) {
  return padchar.repeat(this.length > num ? 0 : (num - this.length)) + this;
};
if(!String.prototype.repeat) {
  String.prototype.repeat = function(count) {
    'use strict';
    if(this == null) {
      throw new TypeError('can\'t convert ' + this + ' to object');
    }
    var str = '' + this;
    count = +count;
    if(count != count) {
      count = 0;
    }
    if(count < 0) {
      throw new RangeError('repeat count must be non-negative');
    }
    if(count == Infinity) {
      throw new RangeError('repeat count must be less than infinity');
    }
    count = Math.floor(count);
    if(str.length == 0 || count == 0) {
      return '';
    }
    // 确保 count 是一个 31 位的整数。这样我们就可以使用如下优化的算法。
    // 当前（2014年8月），绝大多数浏览器都不能支持 1 << 28 长的字符串，所以：
    if(str.length * count >= 1 << 28) {
      throw new RangeError('repeat count must not overflow maximum string size');
    }
    var rpt = '';
    for(;;) {
      if((count & 1) == 1) {
        rpt += str;
      }
      count >>>= 1;
      if(count == 0) {
        break;
      }
      str += str;
    }
    return rpt;
  }
}
if(!String.prototype.includes) {
  String.prototype.includes = function(search, start) {
    'use strict';
    if(typeof start !== 'number') {
      start = 0;
    }

    if(start + search.length > this.length) {
      return false;
    } else {
      return this.indexOf(search, start) !== -1;
    }
  };
}
// Production steps of ECMA-262, Edition 5, 15.4.4.18
// Reference: http://es5.github.io/#x15.4.4.18
// 根据数字id生成文件路径，补齐至9位后每3位数字一级目录
// 例如：id为12345，则文件路径为000/012/345
const getPathById = (id) => {
  var id = (id || 0).toString().padLeft("0", 9);
  var result = '';
  while(id.length > 3) {
    result = '/' + id.slice(-3) + result;
    id = id.slice(0, id.length - 3);
  }
  if(id) { result = id + result; }
  return result;
}

// 对数据进行转换
const getStringByLongNumber = (number) => {
  let result = '';
  if(number < 10000) {
    result = number;
  } else if(number < 100000000) {
    result = (number / 10000).toFixed(1) + '万';
  } else {
    let tmp = parseInt(number / 100000000, 10);
    result = tmp + '亿' + parseInt((number - tmp * 100000000) / 10000) + '万';
  }
  return result;
}

// 路径初始化
const pathInit = (id, imgUrl) => {
  if(id) {
    let path = (imgUrl + "").format(getPathById(id));
    return path;
  }
};

const installData = (data, cb) => {
  // 没有提供参数时直接将数据返回
  if(cb === 'undefind' || typeof cb !== 'function') {
    return data;
  };
  let obj = Array.isArray(data) ? [] : {};
  for(let k in data) {
    if(Array.isArray(data[k])) {
      let tempArr = [];
      for(let i in data[k]) {
        tempArr.push(installData(data[k][i], cb));
      }
      obj[k] = tempArr;
    } else {
      if(typeof data[k] === 'object') {
        obj[k] = installData(data[k], cb);
      } else {
        obj[k] = data[k]; // 当前数据
        obj = cb(k, data[k], obj); //处理当前数据
      }
    }
  }
  return obj;
}

const formatDate = (date, fmt) => {
  date = new Date(date);
  if(/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  var o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  }

  for(var i in o) {
    if(new RegExp('(' + i + ')').test(fmt)) {
      var str = o[i] + '';
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1 ? str : str.padLeft('0', 2)));
    }
  }
  return fmt;
}

const getTimeSpan = (data, closer) => {
  data = parseInt(data, 10);
  let getTimepan = parseInt((new Date().getTime() - data) / 1000);
  let day = Math.floor(getTimepan / 86400);
  let hour = Math.floor((getTimepan - day * 86400) / 3600);
  let minute = Math.floor((getTimepan - day * 86400 - hour * 3600) / 60);
  let second = Math.floor(getTimepan - day * 86400 - hour * 3600 - minute * 60);
  let str = '';
  if(closer) {
    if(day > 9) {
      return this.formatDate(data, 'yyyy.MM.dd') + '日';
    }
    if(day > 0) {
      return day + '天前';
    }
    if(hour > 0) {
      return hour + '小时前';
    }
    if(minute > 0) {
      return minute + '分钟前';
    }
    return '1分钟内';
  } else {
    return formatDate(data, 'yyyy-MM-dd');
  }
}

const detailTime = (update_time, time) => {
  let that = this;
  var dateTime = new Date(update_time);
  var year = dateTime.getFullYear();
  var month = dateTime.getMonth() + 1;
  var day = dateTime.getDate();
  var hour = dateTime.getHours();
  var minute = dateTime.getMinutes();
  var second = dateTime.getSeconds();
  var now = new Date();

  if(time) {
    if(minute < 10) {
      minute = '0' + minute
    }
    return hour + ':' + minute
  }

  var milliseconds = 0;
  var timeSpanStr;

  milliseconds = now - update_time;

  if(milliseconds <= 1000 * 60 * 1) {
    timeSpanStr = '刚刚';
  } else if(1000 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60) {
    timeSpanStr = Math.round((milliseconds / (1000 * 60))) + '分钟前';
  } else if(1000 * 60 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24) {
    timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60)) + '小时前';
  } else if(1000 * 60 * 60 * 24 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24 * 12) {
    timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60 * 24)) + '天前';
  } else if(milliseconds > 1000 * 60 * 60 * 24 * 12 && year == now.getFullYear()) {
    if(month < 10) {
      timeSpanStr = year + '.' + '0' + month + '.' + day;
    } else {
      timeSpanStr = year + '.' + month + '.' + day;
    }
  } else {
    if(month < 10) {
      timeSpanStr = year + '.' + '0' + month + '.' + day;
    } else {
      timeSpanStr = year + '.' + month + '.' + day;
    }
  }
  return timeSpanStr
}

/**
 * 存储localStorage
 * setStore('name', obj)
 */
const setStore = (name, content) => {
  if(!name) return;
  if(typeof content !== 'string') {
    content = JSON.stringify(content);
  }
  window.localStorage.setItem(name, content);
}

/**
 * 获取localStorage
 * setStore('name');
 */
const getStore = name => {
  if(!name) return;
  return JSON.parse(window.localStorage.getItem(name));
}

/**
 * 删除localStorage
 * remove('name');
 */
const removeStore = name => {
  if(!name) return;
  window.localStorage.removeItem(name);
}

const deepClone = (data) => {
  var copy;
  switch(typeof data) {
    case 'number':
    case 'string':
    case 'boolean':
      copy = data;
      break;
    case 'object':
      if(data == null) {
        copy = null
      } else if(toString.apply(data) === '[object Array]') {
        copy = [];
        for(var i in data) {
          copy = copy.concat(deepClone(data[i]));
        };
      } else {
        copy = {};
        for(var j in data) {
          copy[j] = deepClone(data[j]);
        }
      }
  }
  return copy;
}

const objToString = (obj, keys) => {
  var n = keys.length,
    key = [];
  while(n--) {
    key.push(obj[keys[n]]);
  }
  return key.join('|');
}
const uniqeByKeys = (array, keys) => {
  var arr = [];
  var hash = {};
  for(var i = 0, j = array.length; i < j; i++) {
    var k = objToString(array[i], keys);
    if(!(k in hash)) {
      hash[k] = true;
      arr.push(array[i]);
    }
  }
  return arr;
}

const tabInit = (data) => {
  let arr = [];
  data.forEach((v, k) => {
    arr.push(v.sort_group)
  })
  return arr
}


const swipeImgInit = (res, imgUrl) => {
  let arr = [];
  res.forEach((v, i) => {
    let obj = {};
    obj['src'] = pathInit('news', v.id, imgUrl);
    if(/^(https?\:)/.test(v.comic_id)) {
      obj['isFlag'] = false
    } else {
      obj['isFlag'] = true
    }
    obj['url'] = v.comic_id;
    obj['desc'] = v.slide_desc;
    arr.push(obj);
  });
  return arr;
}

const rankListInit = (data, imgUrl) => {
  data.forEach((v, i) => {
    v["src"] = pathInit(v.comic_id, imgUrl);
  });
  return data;
};
const classImg = (data, imgUrl) => {
  data.forEach(item => {
    item.data.forEach(v => {
      v['src'] = pathInit('sort', v.id, imgUrl);
    })
  })
  return data;
}

const UrlEncode = (str) => {
  str = (str + '').toString();

  return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').
  replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
}

const dataURLtoBlob = (dataurl) => {
  var arr = dataurl.split(','),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while(n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
}

const bd_share = () => {
  if(!window._bd_share_config) {
    window._bd_share_config = {
      "common": {
        "bdSnsKey": {},
        // "bdText":"",
        "bdMini": "2",
        "bdMiniList": [
          // "mshare",
          "sqq",
          "qzone",
          "tsina",
        ],
        // "bdPic":"",
        "bdStyle": "1",
        "bdSize": "32"
      },
      "share": {}
    };
    let dad = document.getElementsByTagName('head')[0] || body;
    let child = dad.appendChild(document.createElement('script'));
    child.src = 'http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion=' + ~(-new Date() / 36e5);
  } else {
    window._bd_share_main.init();
  }
}
const score = data => {
  data.forEach(v => {
    v.score = (v.score / 10).toFixed(1);
  })
  return data
}
const initAcDetail = (res) => {
  console.log(res);
  let dataList = {};
  res.list.forEach(item => {
    item['date'] = getTimeSpan(item.updatetime);
    item['time'] = detailTime(item.updatetime, true)
    let dateArr = item.date.split('-');
    let y = dateArr[0],
      m = dateArr[1],
      d = dateArr[2];
    item['day'] = d;
    if(!dataList[y]) {
      dataList[y] = {};
    }
    if(!dataList[y][m]) {
      dataList[y][m] = [];
      dataList[y][m].push(item);
    } else {
      dataList[y][m].push(item);
    }
  })
  console.log(dataList);
  return dataList;
}